package com.luo.d3s.ec.infrastructure.database.convertor;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.luo.d3s.ec.domain.goods.model.*;
import com.luo.d3s.ec.infrastructure.database.dataobject.GoodsDo;
import com.luo.d3s.share.model.BizId;
import com.luo.d3s.share.model.Price;

import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 商品对象转换器
 *
 * @author luohq
 * @date 2022-12-21 10:30
 */
public class GoodsConvertor {

    /**
     * 转换商品实体为数据对象
     *
     * @param goods 商品实体
     * @return 商品数据对象
     */
    public static GoodsDo toGoodsDo(Goods goods) {
        GoodsDo goodsDo = new GoodsDo();
        goodsDo.setId(goods.getId().getValue());
        goodsDo.setCategoryId(goods.getCategoryId().getValue());
        goodsDo.setGoodsName(goods.getGoodsName().getValue());
        goodsDo.setManufactureDate(goods.getGoodsSpec().getManufactureDate());
        goodsDo.setExpirationDate(goods.getGoodsSpec().getExpirationDate());
        goodsDo.setGoodsWeight(goods.getGoodsSpec().getGoodsWeight().getWeight());
        goodsDo.setGoodsWeightUnit(goods.getGoodsSpec().getGoodsWeight().getUnit().getValue());
        goodsDo.setGoodsDesc(goods.getGoodsSpec().getGoodsDesc());
        goodsDo.setGoodsPrice(goods.getGoodsPrice().getValue());
        goodsDo.setGoodsStatus(goods.getGoodsStatus().getValue());
        goodsDo.setCreateTime(goods.getCreateTime());
        goodsDo.setUpdateTime(goods.getUpdateTime());
        return goodsDo;
    }

    /**
     * 转换商品数据对象为实体
     *
     * @param goodsDo 商品数据对象
     * @param tagIds  商品标签ID集合
     * @return 商品实体
     */
    public static Goods toGoods(GoodsDo goodsDo, Set<Long> tagIds) {
        Set<BizId> tagIdSet = Collections.emptySet();
        if (!CollectionUtils.isEmpty(tagIdSet)) {
            tagIdSet = tagIds.stream().map(BizId::of).collect(Collectors.toSet());
        }
        Goods goods = new Goods(
                BizId.of(goodsDo.getId()),
                tagIdSet,
                BizId.of(goodsDo.getCategoryId()),
                GoodsName.of(goodsDo.getGoodsName()),
                GoodsSpec.builder()
                        .manufactureDate(goodsDo.getManufactureDate())
                        .expirationDate(goodsDo.getExpirationDate())
                        .goodsWeight(GoodsWeight.builder()
                                .weight(goodsDo.getGoodsWeight())
                                .unit(WeightUnit.of(goodsDo.getGoodsWeightUnit()))
                                .build())
                        .goodsDesc(goodsDo.getGoodsDesc())
                        .build(),
                Price.of(goodsDo.getGoodsPrice()),
                GoodsStatus.of(goodsDo.getGoodsStatus()),
                goodsDo.getCreateTime(),
                goodsDo.getUpdateTime());
        return goods;
    }
}
